package com.schedualnew.mq.util;

import cn.hutool.core.util.XmlUtil;
import com.schedualnew.mq.controller.MQApiController;
import com.schedualnew.mq.dto.exam.ExamApplyDto;
import com.schedualnew.mq.xml.ApplyInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HLHTUtil {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    SimpleDateFormat sdfSecondes = new SimpleDateFormat("yyyyMMddHHmmss");
    SimpleDateFormat sdfMinutes = new SimpleDateFormat("yyyyMMddHHmm");
    private Logger logger = LogManager.getLogger(MQApiController.class);

    public String loadXML(ExamApplyDto examApplyDto) {
        try {
            // 创建一个 DocumentBuilderFactory 对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 通过工厂获取一个 DocumentBuilder 对象
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 使用 DocumentBuilder 对象的 parse() 方法来读取并解析 XML 文件

            byte[] datas = ApplyInfo.xml.getBytes();
            Document document = builder.parse(new ByteArrayInputStream(datas));

            //logger.info("loadxml：" + ApplyInfo.xml);

            //消息创建时间
            Element creationElement = XmlUtil.getElementByXPath("//PRSC_IN010201UV01/creationTime", document);
            creationElement.setAttribute("value", sdf.format(new Date()));

            //预约单流水号
            Element idElement = XmlUtil.getElementByXPath("//PRSC_IN010201UV01/controlActProcess/subject/actAppointment/id", document);
            idElement.setAttribute("extension", sdfSecondes.format(new Date()));

            //预约检查时间
            Element examTime = XmlUtil.getElementByXPath("//PRSC_IN010201UV01/controlActProcess/subject/actAppointment/effectiveTime/any", document);
            examTime.setAttribute("value", examApplyDto.getScheduledTime());

            //患者id
            Element patientId = XmlUtil.getElementByXPath("//PRSC_IN010201UV01/controlActProcess/subject/actAppointment/subject/patient/id/item", document);
            patientId.setAttribute("extension", examApplyDto.getSickId());

            //患者姓名
            Element patientName = XmlUtil.getElementByXPath("//PRSC_IN010201UV01/controlActProcess/subject/actAppointment/subject/patient/patientPerson/name/item/part", document);
            patientName.setAttribute("value", examApplyDto.getName());

            //病人科室编码
            Element deptNo = XmlUtil.getElementByXPath("//PRSC_IN010201UV01/controlActProcess/subject/actAppointment/subject/patient/providerOrganization/id/item", document);
            deptNo.setAttribute("extension", examApplyDto.getDeptCode());

            //病人科室名称
            Element deptName = XmlUtil.getElementByXPath("//PRSC_IN010201UV01/controlActProcess/subject/actAppointment/subject/patient/providerOrganization/name/item/part", document);
            deptName.setAttribute("value", "");

            //执行科室
            Element operateDept = XmlUtil.getElementByXPath("//PRSC_IN010201UV01/controlActProcess/subject/actAppointment/location/serviceDeliveryLocation/id/item", document);
            operateDept.setAttribute("extension", examApplyDto.getPacsExamDept());

            //申请单编号
            Element applyNo = XmlUtil.getElementByXPath("//PRSC_IN010201UV01/controlActProcess/subject/actAppointment/referencedOrder/actOrder/id", document);
            applyNo.setAttribute("extension", examApplyDto.getApplyNo());
            logger.info("loadxml：申请单编号");

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            DOMSource source = new DOMSource(document);
            transformer.transform(source, result);
            String xmlString = writer.toString();
            return xmlString;

        } catch (Exception ex) {
            logger.info("loadxml异常：" + ex.toString());
            return "";
        }
    }


    public String loadAppointXML(ExamApplyDto examApplyDto) {
        try {
            // 创建一个 DocumentBuilderFactory 对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 通过工厂获取一个 DocumentBuilder 对象
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 使用 DocumentBuilder 对象的 parse() 方法来读取并解析 XML 文件

            byte[] datas = ApplyInfo.appointXml.getBytes();
            Document document = builder.parse(new ByteArrayInputStream(datas));

            //logger.info("loadxml：" + ApplyInfo.xml);

            //消息创建时间
            Element creationElement = XmlUtil.getElementByXPath("//PRSC_IN010101UV01/creationTime", document);
            creationElement.setAttribute("value", sdf.format(new Date()));

            //预约单流水号
            Element idElement = XmlUtil.getElementByXPath("//PRSC_IN010101UV01/controlActProcess/subject/actAppointment/id", document);
            idElement.setAttribute("extension", sdfSecondes.format(new Date()));

            //预约检查时间
            Element examTime = XmlUtil.getElementByXPath("//PRSC_IN010101UV01/controlActProcess/subject/actAppointment/effectiveTime/any", document);
            examTime.setAttribute("value", examApplyDto.getScheduledTime());

            //患者id
            Element patientId = XmlUtil.getElementByXPath("//PRSC_IN010101UV01/controlActProcess/subject/actAppointment/subject/patient/id/item", document);
            patientId.setAttribute("extension", examApplyDto.getSickId());

            //患者姓名
            Element patientName = XmlUtil.getElementByXPath("//PRSC_IN010101UV01/controlActProcess/subject/actAppointment/subject/patient/patientPerson/name/item/part", document);
            patientName.setAttribute("value", examApplyDto.getName());

            //病人科室编码
            Element deptNo = XmlUtil.getElementByXPath("//PRSC_IN010101UV01/controlActProcess/subject/actAppointment/subject/patient/providerOrganization/id/item", document);
            deptNo.setAttribute("extension", examApplyDto.getDeptCode());

            //病人科室名称
            Element deptName = XmlUtil.getElementByXPath("//PRSC_IN010101UV01/controlActProcess/subject/actAppointment/subject/patient/providerOrganization/name/item/part", document);
            deptName.setAttribute("value", "");

            //执行科室
            Element operateDept = XmlUtil.getElementByXPath("//PRSC_IN010101UV01/controlActProcess/subject/actAppointment/location/serviceDeliveryLocation/id/item", document);
            operateDept.setAttribute("extension", examApplyDto.getPacsExamDept());

            //申请单编号
            Element applyNo = XmlUtil.getElementByXPath("//PRSC_IN010101UV01/controlActProcess/subject/actAppointment/referencedOrder/actOrder/id", document);
            applyNo.setAttribute("extension", examApplyDto.getApplyNo());
            logger.info("loadxml：申请单编号");

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            DOMSource source = new DOMSource(document);
            transformer.transform(source, result);
            String xmlString = writer.toString();
            return xmlString;

        } catch (Exception ex) {
            logger.info("loadxml异常：" + ex.toString());
            return "";
        }
    }

}
